# # -*- coding: utf-8 -*-
# # 2020.05.19
# # 09:13:22
# # author:mistchan
import collections
from datetime import datetime
import re
from django.shortcuts import redirect, render
from django.utils.deprecation import MiddlewareMixin
from app01 import models
from django.conf import settings


#
# # 封装到Trace类中
class Tracer(object):
    def __init__(self):
        self.user = None
        self.project = None


class AuthTools(object):
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs


class PathTools(object):
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.path_infos = collections.OrderedDict()
        self.path_infos['/home.html/'] = "主页"
        self.path_infos['/customer_list.html/'] = "客户列表"


#
# # 通过中间件+白名单对后台管理、登录的权限进行处理
# # 中间件如果返回值，则用户不能继续往下访问，如果返回None则继续向下进行
# # 之后在setting.py中的MIDDLEWARE中注册middleware.auth.AuthMiddleware
class AuthMiddleware(MiddlewareMixin):
    # 中间件流程，用户请求进来，执行process_request，然后路由匹配，然后执行process_view，然后执行视图函数
    def process_request(self, request):
        """
        如果用户已经登录，则在request中赋值request.tracer
        在前端html文件中可以通过判断：
        如果登录则显示登录的用户名，否则显示登录链接
        {% if request.tracer %}
            <a href="#">{{ request.trace.username }}</a>
        {% else %}
            <a href="{% url 'login' %}">登录</a>
        {% end if %}
        之类，来分条件显示页面
        """
        # 将request.tracer封装到Tracer()类中并实例化
        request.tracer = Tracer()
        request.authtools = AuthTools()
        request.pathtools = PathTools()

        user_info = request.session.get('info', 0)  # 从session中获取user_id的值，如果没有默认为0
        user_id = user_info.get('id') if user_info else 0
        user_object = models.ManagerList.objects.filter(id=user_id).first()  # 以user_id为条件筛选数据库，看有没有这个用户
        request.tracer = user_object  # 将查询结果（queryset类型，后续可以通过.id之类继续取值）赋值给request.tracer

        # 白名单：没有登录都可以访问的url，直接放行
        """
        在setting.py中添加
        白名单，无需登录就可以访问的页面
        WHITE_REGEX_URL_LIST = [
            "/home.html/",
            "/login.html/",
        ]
        """
        cus_info = request.session.get('cus_info', 0)
        if cus_info:
            request.pathtools.path_infos[f"/customer/{cus_info.get('pid')}/details.html/"] = cus_info.get('name')
        # 1、获取当前用户访问的URL
        request_url = request.path_info
        # 2、检查URL是否在白名单中

        if request_url not in request.pathtools.path_infos.keys():
            request.pathtools.path_infos[request_url] = "当前页"

        if request_url in settings.WHITE_REGEX_URL_LIST:
            if request.tracer and request_url in ['/login.html/', ]:
                return redirect('/home.html/')
            # 3、如果在，则可以继续向后访问；
            return  # 表示return None 中间件返回None则继续往下进行
        # 4、如果不在则进行判断是否已登录，已登录则继续；未登录则返回登录页面。
        if not request.tracer:
            return redirect('/login.html/')


        auth_lever = request.tracer.auth_level

        if request_url.startswith("/admin") and auth_lever not in [1, 2]:
            return redirect('/customer_list.html/')

        if request_url.startswith("/buying") and request_url.endswith("edit.html/"):
            auth_lever = request.tracer.auth_level
            buying_id = re.search(r'buying/(\d+)/edit.html/', request_url).group(1)
            result = models.BuyingList.objects.filter(buying_id=buying_id).first()

            if request.tracer.id != result.operator.id and auth_lever != 1:

                request.authtools.info = result.pid.pid
                return render(request, "error.html", {"error": "无修改权限：只能修改本人生成的订单！", "pid": result.pid.pid})
            else:
                request.authtools = result
                return
